/**
 * 
 */
package com.jxc.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.dao.GoodsDaoI;
import com.jxc.dao.MemberDaoI;
import com.jxc.dao.RemindWarnDaoI;
import com.jxc.dao.RepertoryDaoI;
import com.jxc.model.po.RemindWarn;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VGoods;
import com.jxc.model.vo.VMember;
import com.jxc.model.vo.VRemindWarn;
import com.jxc.model.vo.VRepertory;
import com.jxc.service.RemindWarnServiceI;
import com.jxc.util.ExceptionUtil;

/**
 * @author Tino
 * 
 */
@Service("remindWarnService")
public class RemindWarnServiceImpl implements RemindWarnServiceI {
	private final static Logger logger = Logger.getLogger(RemindWarnServiceImpl.class);

	@Autowired
	private BaseDaoI<RemindWarn> remindWarnDao;
	@Autowired
	private GoodsDaoI goodsDao;
	@Autowired
	private MemberDaoI memberDao;
	@Autowired
	private RepertoryDaoI repertoryDao;
	@Autowired
	private RemindWarnDaoI threadRemindWarnDao;

	@Override
	public List<VRemindWarn> combobox(VRemindWarn vrw) {
		return this.changeModel(this.find(vrw));
	}

	@Override
	public DataGrid datagrid(VRemindWarn vrw) {
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vrw)));
		dg.setTotal(this.total(vrw));
		return dg;
	}

	@Override
	public void delete(String ids) {
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					RemindWarn rw = this.remindWarnDao.get(RemindWarn.class, Long.parseLong(id.trim()));
					if (rw != null) {
						remindWarnDao.delete(rw);
					}
				}
			}
		}
	}

	@Override
	public void save(VRemindWarn vrw) {
		RemindWarn rw = new RemindWarn();
		BeanUtils.copyProperties(vrw, rw);
		if (vrw.getRid() != null) {
			rw.setRepertory(new Repertory(vrw.getRid()));
		}
		if (vrw.getUid() != null) {
			rw.setUser(new User(vrw.getUid()));
		}
		if (vrw.getCuid() != null) {
			rw.setConfirmUser(new User(vrw.getCuid()));
		}
		this.remindWarnDao.save(rw);
	}
	
	private void threadSave(VRemindWarn vrw) {
		RemindWarn rw = new RemindWarn();
		BeanUtils.copyProperties(vrw, rw);
		if (vrw.getRid() != null) {
			rw.setRepertory(new Repertory(vrw.getRid()));
		}
		if (vrw.getUid() != null) {
			rw.setUser(new User(vrw.getUid()));
		}
		if (vrw.getCuid() != null) {
			rw.setConfirmUser(new User(vrw.getCuid()));
		}
		this.threadRemindWarnDao.save(rw);
	}

	@Override
	public void update(VRemindWarn vrw) {
		RemindWarn rw = remindWarnDao.get(RemindWarn.class, vrw.getId());
		BeanUtils.copyProperties(vrw, rw, new String[] { "id" });
		if (vrw.getRid() != null) {
			rw.setRepertory(new Repertory(vrw.getRid()));
		}
		if (vrw.getUid() != null) {
			rw.setUser(new User(vrw.getUid()));
		}
		if (vrw.getCuid() != null) {
			rw.setConfirmUser(new User(vrw.getCuid()));
		}
		this.remindWarnDao.update(rw);
	}

	private List<VRemindWarn> changeModel(List<RemindWarn> rws) {
		List<VRemindWarn> vrws = new ArrayList<VRemindWarn>();
		if (rws != null && rws.size() > 0) {
			for (RemindWarn rw : rws) {
				VRemindWarn vrw = new VRemindWarn();
				BeanUtils.copyProperties(rw, vrw);
				if (rw.getUser() != null) {
					User user = rw.getUser();
					vrw.setUid(user.getId());
					vrw.setUsername(user.getUsername());
				}
				if (rw.getConfirmUser() != null) {
					User confirmUser = rw.getConfirmUser();
					vrw.setCuid(confirmUser.getId());
					vrw.setCuname(confirmUser.getUsername());
				}
				if (rw.getRepertory() != null) {
					Repertory repertory = rw.getRepertory();
					vrw.setRid(repertory.getId());
					vrw.setRname(repertory.getName());
				}
				vrws.add(vrw);
			}
		}
		return vrws;
	}

	private List<RemindWarn> find(VRemindWarn vrw) {
		String hql = "from RemindWarn t where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vrw, hql, values);

		if (vrw.getSort() != null && vrw.getOrder() != null) {
			hql += " order by " + vrw.getSort() + " " + vrw.getOrder();
		}
		return remindWarnDao.find(hql, values, vrw.getPage(), vrw.getRows());
	}

	private Long total(VRemindWarn vrw) {
		String hql = "select count(*) from RemindWarn t where 1=1 ";
		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vrw, hql, values);
		return this.remindWarnDao.count(hql, values);
	}

	private String addWhere(VRemindWarn vrw, String hql, List<Object> values) {
		if (vrw.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vrw.getId());
		}

		if (vrw.getUid() != null) {
			hql += " and t.user.id = ? ";
			values.add(vrw.getUid());
		}

		if (vrw.getRid() != null) {
			hql += " and t.repertory.id = ? ";
			values.add(vrw.getRid());
		}

		if (vrw.getCuid() != null) {
			hql += " and t.confirmUser.id = ? ";
			values.add(vrw.getCuid());
		}

		if (vrw.getBeginDate() != null) {
			hql += " and t.time >= ? ";
			values.add(vrw.getBeginDate());
		}

		if (vrw.getEndDate() != null) {
			hql += " and t.time <= ? ";
			values.add(vrw.getEndDate());
		}

		if (vrw.getIsDone() != null) {
			hql += " and t.isDone = ? ";
			values.add(vrw.getIsDone());
		}

		return hql;
	}

	@Override
	public void doJob() {
		logger.info("提醒预警任务开始执行.");
		try {

			/*
			 * --------------------------------------------------------------------------------------
			 * 库存负数告警
			 * --------------------------------------------------------------------------------------
			 */
			VGoods vgParam = new VGoods();
			List<VGoods> vgoodz = goodsDao.combobox(vgParam);
			for (VGoods vgoods : vgoodz) {
				if (vgoods.getAmount() < 0) {
					VRemindWarn vrw = new VRemindWarn();
					vrw.setTime(new Date());
					vrw.setContent("商品[名称：" + vgoods.getName() + "，条码：" + vgoods.getBarcode() + "]库存负数告警，请及时进货！");
					vrw.setIsDone(false);
					vrw.setRid(vgoods.getRid());

					VRepertory vrParam = new VRepertory();
					vrParam.setId(vgoods.getRid());
					List<VRepertory> vrs = repertoryDao.list(vrParam);
					VRepertory vr = vrs.get(0);
					vrw.setUid(vr.getUid());
					this.threadSave(vrw);
				}
			}

			VMember vmParam = new VMember();
			List<VMember> vms = memberDao.combobox(vmParam);
			for (VMember vm : vms) {

				/*
				 * --------------------------------------------------------------------------------------
				 * 会员生日提醒
				 * --------------------------------------------------------------------------------------
				 */
				if (vm.getBirthdayA() != null) {
					String birthdayStr = new SimpleDateFormat("yyyy-MM-dd").format(vm.getBirthdayA());
					String todayString = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
					if (birthdayStr.equals(todayString)) {
						VRemindWarn vrw = new VRemindWarn();
						vrw.setTime(new Date());
						vrw.setContent("会员[姓名：" + vm.getName() + "，编号：" + vm.getSerial() + "]今天生日，请对他/她关怀一下！");
						vrw.setIsDone(false);
						vrw.setUid(vm.getUid());
						this.threadSave(vrw);
					}
				}

			}
		} catch (Exception e) {
			logger.info(ExceptionUtil.getExceptionMessage(e));
		}
	}

}
